﻿using ShareRss.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ShareRss.Dll
{
    public class ReadRss
    {
        public static XmlModel AddCondition(MainModel model)
        {
            string url = "https://share.dmhy.org/topics/rss/rss.xml?order=";
            if (!string.IsNullOrEmpty(model.Class) && model.Class != "0")
            {
                url += $"&sort_id={model.Class}";
            }
            if (!string.IsNullOrEmpty(model.Name))
            {
                url += $"&keyword={model.Name}";
            }
            if (!string.IsNullOrEmpty(model.Subtitle) && model.Subtitle != "0")
            {
                url += $"&team_id={model.Subtitle}";
            }
            return UrlReadRss(url, model);
        }
        private static XmlModel UrlReadRss(string url, MainModel xmlmodel)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(url);
            XmlNodeList item = doc.SelectNodes("/rss/channel");
            XmlModel model = new XmlModel();
            model.Title = item[0]["title"].InnerText;
            model.Link = item[0]["link"].InnerText;
            model.Description = item[0]["description"].InnerText;
            model.Language = item[0]["language"].InnerText;
            model.PubDate = item[0]["pubDate"].InnerText;
            model.Class = xmlmodel.Class;
            model.Subtitle = xmlmodel.Subtitle;
            model.Name = xmlmodel.Name;
            int count = item[0].ChildNodes.Count;
            for (int i = 0; i < count; i++)
            {
                if (item[0].ChildNodes[i].Name != "item") continue;
                Item itemOne = new Item()
                {
                    Title = item[0].ChildNodes[i]["title"].InnerText,
                    Link = item[0].ChildNodes[i]["link"].InnerText,
                    PubDate =DateTime.Parse(item[0].ChildNodes[i]["pubDate"].InnerText),
                    Description = item[0].ChildNodes[i]["description"].InnerText,
                    Enclosure = item[0].ChildNodes[i]["enclosure"].Attributes["url"].Value,
                    Author = item[0].ChildNodes[i]["author"].InnerText,
                    Guid = item[0].ChildNodes[i]["guid"].InnerText,
                    Category = item[0].ChildNodes[i]["category"].InnerText
                };
                model.Item.Add(itemOne);
            }
            return model;
        }

    }
}
